package com.wyz.calibur.infrastructure.utils;

import cn.hutool.crypto.SecureUtil;
import com.wyz.calibur.constant.AuthConstant;
import com.wyz.calibur.enums.RedisKeyEnum;
import com.wyz.calibur.infrastructure.config.security.UserAuthInfo;
import com.wyz.calibur.infrastructure.config.security.UserAuthInfoDTO;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 上下文工具类
 * @Author: wei yz
 * @Date: 2022/1/24 13:53
 */
@Component
public class ContextUtil {

    private static final Logger log = LoggerFactory.getLogger(ContextUtil.class);

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 从请求头中拿到token
     *
     * @param
     * @return
     * @author wei yz
     */
    public static String getToken(HttpServletRequest request) {
        String token = null;
        // 拿到请求头
        String authHeader = request.getHeader(AuthConstant.TOKEN_HEADER);
        // 是否为“Bearer ” 开头的字符串
        if (StringUtils.isNotBlank(authHeader) && authHeader.startsWith(AuthConstant.TOKEN_HEAD)) {
            // 根据"Bearer "取出token
            token = authHeader.substring(AuthConstant.TOKEN_HEAD.length());
        }
        log.info("==> 请求头：{} ,token：{}", authHeader, token);
        return token;
    }

    /**
     * 获取当前用户的信息
     *
     * @param
     * @return
     * @author wei yz
     */
    public UserAuthInfo currentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserAuthInfo userAuthInfo = (UserAuthInfo) authentication.getPrincipal();
        // 获取token
        String token = (String) redisUtil.get(RedisKeyEnum.LOGIN_VOUCHER.getKey() + SecureUtil.md5(userAuthInfo.getUsername()));
        // 获取用户信息
        UserAuthInfoDTO authInfoDTO = (UserAuthInfoDTO) redisUtil.get(RedisKeyEnum.USER_INFO_BASE.getKey() + token);
        log.info("==> 缓存中的信息：{}", authInfoDTO);
        return (UserAuthInfo) authentication.getPrincipal();
    }

}
